import {Component, HostBinding, OnInit, ViewChild} from '@angular/core';
import {defaultRouteAnim} from '../../anim/router.anim';
import {TorrentService} from '../../service/torrent.service';
import {MatDialog, MatPaginator, MatSnackBar} from '@angular/material';
import {UserService} from '../../service/user.service';
import {PostService} from '../../service/post.service';
import {errorSnackBar, errSnackbar} from '../../util/snack.util';
import {Post} from '../../model/post';
import {animate, state, style, transition, trigger} from '@angular/animations';

@Component({
  selector: 'app-torrents',
  templateUrl: './torrents.component.html',
  styleUrls: ['./torrents.component.css'],
  animations: [defaultRouteAnim,
    trigger('detailExpand', [
      state('collapsed', style({height: '0px', minHeight: '0'})),
      state('expanded', style({height: '*'})),
      transition('expanded <=> collapsed', animate('225ms cubic-bezier(0.4, 0.0, 0.2, 1)'))])
  ]
})
export class TorrentsComponent implements OnInit {
  @HostBinding('@routeAnim') routeAnim;

  dataSource: Post[];
  displayedColumns = ['type', 'title'];
  expandedElement: Post | null;

  @ViewChild(MatPaginator, {static: true}) paginator: MatPaginator;

  resultsLength = 0;

  constructor(
    public snackBar: MatSnackBar, private dialog: MatDialog,
    public torrentService: TorrentService, public userService: UserService, public postService: PostService) {
  }

  ngOnInit() {
    this.postService.count(this.userService.user.token).subscribe(count => {
      this.resultsLength = count.count;
      // this.getPageSizeOptions(result.data);
    }, error1 => {
      errorSnackBar(this.snackBar, error1);
    });
    this.list(1);
    this.paginator.page.subscribe((event) => {
      this.list(event.pageIndex + 1);
    });
  }

  list(index: number) {
    this.postService.list(this.userService.user.token, index).subscribe(postArray => {
      this.dataSource = postArray;
    }, error1 => {
      errorSnackBar(this.snackBar, error1);
    });
  }

  downloadTorrent(tid: number) {
    this.torrentService.download(tid, this.userService.user.token).subscribe(result => {
      const link = document.createElement('a');
      const blob = new Blob([result.body], {type: 'application/x-bittorrent'});
      link.setAttribute('href', window.URL.createObjectURL(blob));
      const fileName = result.headers.get('Content-Disposition').split('filename=')[1];
      link.setAttribute('download', decodeURI(fileName).replace(/"/g, ''));
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }, error1 => {
      errSnackbar(this.snackBar, '没有该种子');
    });
  }
}
